List comprehension


In [1]:
lst1 = [x for x in range(10)]
lst1


Out[1]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [2]:
lst2 = [chr(x) for x in range(97,123) if x%2==0]
lst2


Out[2]:
['b', 'd', 'f', 'h', 'j', 'l', 'n', 'p', 'r', 't', 'v', 'x', 'z']

In [3]:
[y for x in range(3) for y in range(x) if y%2==0]


Out[3]:
[0, 0]

Lambda function


In [4]:
# square
f1 = lambda v1: v1 ** 2
f1(5)


Out[4]:
25

In [5]:
# power with two inputs
f2 = lambda v1, v2: v1 ** v2
f2(5, 2)


Out[5]:
25

In [6]:
# checking even numbers one by one
f3 = lambda v1: [v1 if v1%2==0 else 0]
print(f3(9))
print(f3(8))


[0]
[8]

In [12]:
# Checking if a number is present in list
f4 = lambda v1, v2: [545 for i in v2 if i == v1]
f4(8,[9,8])


Out[12]:
[545]

map - applies a function on all the values of sequence

Syntax - $map(func, seq)$

return a sequence


In [8]:
# Finding square of every value
f5 = lambda v1: v1**2
list(map(f5,[2,5]))


Out[8]:
[4, 25]

filter - returns the value for which condition holds True

Syntax - $filter(func, seq)$

returns a sequence


In [13]:
# finding even numbers
f6 = lambda v1: v1%2
list(filter(f6,[2,5,6]))


Out[13]:
[5]

reduce - continually applies the function func() to the sequence seq.

Syntax: $reduce(func, seq)$

returns a single value


In [10]:
# Finding the greatest number
from functools import reduce
f7 = lambda v1, v2: v1 if v1>v2 else v2
reduce(f7,[2,5,1,90,48])


Out[10]:
90

Anonymous function


In [11]:
reduce(lambda v1, v2: v1 if v1>v2 else v2,[2,5,1,90,48])


Out[11]:
90